const allStockValueSpan = document.getElementById("stockValue");
const stockTable        = document.getElementById("stockTable");
const tableJsWarning    = document.getElementById("tableJSWarning");

function updateValues (values) {
  tableJsWarning.hidden = true

  // update the value of allStocks
  allStockValueSpan.textContent = values["_all"];
  delete values["_all"];

  var newStockTBody = document.createElement("tbody");
  if (Object.keys(values).length === 0) {
    const noStocks = document.createElement("td");
    noStocks.textContent = "Du besitzt keine Aktien.";
    noStocks.setAttribute("colspan", "5");
    newStockTBody.appendChild(noStocks);
  } else {
    var stockValueField, stockAmountField, stockAmountValueField;
    for (var stock in values) {
      var newRow = document.createElement("tr");
      var data = [];
      // push returns the new size, so in theory this could be minimized further
      // this was intentionally not done here to maintain readability
      data.push(document.createElement("td"));
      data[data.length-1].textContent = values[stock]["description"];
      data.push(document.createElement("td"));
      data[data.length-1].textContent = stock;
      data.push(document.createElement("td"));
      data[data.length-1].textContent = values[stock]["value"];
      data.push(document.createElement("td"));
      data[data.length-1].textContent = values[stock]["amount"];
      data.push(document.createElement("td"));
      data[data.length-1].textContent = values[stock]["total_value"];

      // add selling
      data.push(document.createElement("button"));
      data[data.length-1].textContent = "Verkaufe eine!";
      data[data.length-1].setAttribute("onClick", "sellStocks(\""+stock+"\")");

      // push all to the row
      data.forEach(function (item) { newRow.appendChild(item); });
      // add row to the tbody
      newStockTBody.appendChild(newRow);
    }
  }
  stockTable.replaceChild(newStockTBody, stockTable.getElementsByTagName("tbody")[0])
  startUpdating();
}

